package de.jmda.util.gui.fx;

import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javafx.scene.image.Image;

import javax.lang.model.element.Element;

import org.apache.log4j.Logger;

import de.jmda.gui.ImageFilenameFactory;
import de.jmda.util.gui.awt.graphics.IconProvider;

public abstract class ImageFactory
{
	private final static Logger LOGGER = Logger.getLogger(ImageFactory.class);

	private final static Map<String, Image> FILENAME_TO_IMAGE =
			new HashMap<String, Image>();
	
	private final static String PATH = "icon/";

	/**
	 * @param element
	 * @param filenameSuffix
	 * @return image if image file can be loaded, null otherwise
	 */
	public static Image getImage(Element element, String filenameSuffix)
	{
		String imageFilename =
				ImageFilenameFactory.getImageFilename(element, filenameSuffix);
		
		Image result = FILENAME_TO_IMAGE.get(imageFilename);

		if (result == null)
		{
			URL url =
					IconProvider.class//.getClassLoader()
					            .getResource(PATH + imageFilename);

			// check existence of url
			try
      {
      	URI uri = url.toURI();

      	File file = new File(uri);
				
				if (file.exists() == false)
				{
					LOGGER.error("file " + file.getAbsolutePath() + " does not exist");
					return null;
				}
      }
      catch (URISyntaxException e)
      {
      	LOGGER.error("failure creating URI from " + url, e);
      	return null;
      }

			result = new Image(url.toString());

			FILENAME_TO_IMAGE.put(imageFilename, result);
		}

		return result;
	}
}